<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="科室名称">
          <el-input v-model="searchForm.departmentName" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddDepartment">新增科室</el-button>
    </div>

    <!-- 科室表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="departmentId" label="科室ID" width="80" />
      <el-table-column prop="name" label="科室名称" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
          <el-button type="warning" size="small" @click="handleEditDepartment(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteDepartment(scope.row.departmentId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑科室对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
      <el-form :model="currentForm" :rules="rules" ref="departmentFormRef">
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="currentForm.name" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="currentForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 科室详情对话框 -->
    <el-dialog :title="currentDepartment.name" v-model="dialogDetailVisible" width="70%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="科室ID">{{ currentDepartment.departmentId }}</el-descriptions-item>
        <el-descriptions-item label="科室名称">{{ currentDepartment.name }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ currentDepartment.description }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentDepartment.createTime }}</el-descriptions-item>
      </el-descriptions>

      <h3 class="mt-20">所属医生列表</h3>
      <el-table :data="currentDepartment.doctorVoList" border style="width: 100%">
        <el-table-column prop="doctorId" label="医生ID" width="80" />
        <el-table-column prop="doctorRealName" label="医生姓名" />
        <el-table-column prop="title" label="职称" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="avatar" label="头像">
          <template #default="scope">
            <img :src="scope.row.avatar" alt="avatar" style="width: 50px; height: 50px" />
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="dialogDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import {departmentDeleteOne, departmentInsertOne, departmentSelectPage, departmentUpdateOne} from "@/api/department.js";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索条件
const searchForm = reactive({
  departmentName: '',
});

// 新增/编辑对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  departmentId: 0,
  name: '',
  description: '',
});
const departmentFormRef = ref(null);

// 验证规则
const rules = {
  name: [{ required: true, message: '科室名称不能为空', trigger: 'blur' }],
};

// 详情对话框
const dialogDetailVisible = ref(false);
const currentDepartment = ref({});

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      departmentName: searchForm.departmentName,
    };
    if (searchForm.departmentName === '') {
      delete params.departmentName;
    }
    const response = await departmentSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    console.log(error)
    ElMessage.error('获取科室列表失败');
  }
};

// 新增科室
const handleAddDepartment = () => {
  dialogTitle.value = '新增科室';
  dialogVisible.value = true;
  resetForm();
};

// 编辑科室
const handleEditDepartment = (row) => {
  dialogTitle.value = '编辑科室';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
};

// 删除科室
const handleDeleteDepartment = (departmentId) => {
  ElMessageBox.confirm('确认删除该科室?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await departmentDeleteOne(departmentId);
      ElMessage.success('删除成功');
      await fetchDepartments();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存科室（新增/编辑）
const handleSubmit = () => {
  departmentFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.departmentId) {
          // 编辑
          await departmentUpdateOne(currentForm);
        } else {
          // 新增
          await departmentInsertOne(currentForm);
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchDepartments();
        resetForm();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchDepartments();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchDepartments();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchDepartments();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  Object.assign(searchForm, {
    departmentName: '',
  });
  fetchDepartments();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    departmentId: 0,
    name: '',
    description: '',
  });
  departmentFormRef.value?.clearValidate();
};

// 显示科室详情
const handleViewDetail = (department) => {
  currentDepartment.value = department;
  dialogDetailVisible.value = true;
};

// 关闭详情对话框时重置数据
const handleCloseDetail = () => {
  currentDepartment.value = {};
};

onMounted(() => {
  fetchDepartments();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}
.action-bar {
  margin-bottom: 15px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.mt-20 {
  margin-top: 20px;
}
</style>
